/*
 * Copyright 2009 Eat Local Food, LLC
 * Copyright (c) 2007 osCommerce (this file was written after
 * code review of osCommerce).
 *
 * This file is part of gwtCommerce.
 *
 * gwtCommerce is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * gwtCommerce is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with gwtCommerce.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.elf.gwt.admin.client.components;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.elf.gwt.admin.client.AdminComponentController;
import com.elf.gwt.common.client.access.RequestParameter;
import com.elf.gwt.common.client.model.TermsAndConditionsLabelsModel;
import com.elf.gwt.common.client.model.TermsAndConditionsModel;
import com.elf.gwt.common.client.utils.CommonUtils;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.InlineHTML;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

/**
 *  
 */
public class TermsAndConditionsComponent extends EditTableComponent
{	
	protected static final String ToggleRequired = "ToggleRequired";
	protected static final String Insert = "Insert";

	protected List<TermsAndConditionsModel> termsAndConditionsModels;
	protected TermsAndConditionsModel selectedTermsAndConditionsModel;
	protected DialogBox textDialogBox = null;
	protected DialogBox dialogBox = null;
	protected DialogBox parentDialogBox = null;

	protected static TermsAndConditionsLabelsComponent termsAndConditionsLabelsComponent;

	/**
	 * Constructor
	 */
	public TermsAndConditionsComponent(AdminComponentController controller, String stylePrefix)
	{
		super(controller, stylePrefix);
		parentDialogBox = null;
		termsAndConditionsModels = new ArrayList<TermsAndConditionsModel>();
		paginate = true;
		tableType = "terms and conditions";
		if (termsAndConditionsLabelsComponent == null) termsAndConditionsLabelsComponent = (TermsAndConditionsLabelsComponent)controller.getComponent("TermsAndConditionsLabelsComponent");

	}
	
	public TermsAndConditionsComponent(DialogBox parentDialogBox,  AdminComponentController controller, String stylePrefix)
	{
		this(controller, stylePrefix);
		this.parentDialogBox = parentDialogBox;
	}

	public void additionalRequestParameters()
	{
		if (action != null && action.equals(ToggleRequired))
		{
			addRequestParameter(new RequestParameter("tAndCId", selectedTermsAndConditionsModel.getId()));
		}
		super.additionalRequestParameters();
	}

	protected void buildMetaModel(JSONObject jsonObject) throws Exception
	{
		super.buildMetaModel(jsonObject);
	}

	protected void buildModel(JSONArray jsonArray) throws Exception
	{
		termsAndConditionsModels.clear();
		super.buildModel(jsonArray);
	}

	protected void buildModel(JSONObject jsonObject) throws Exception
	{
		TermsAndConditionsModel model = new TermsAndConditionsModel(jsonObject);
		termsAndConditionsModels.add(model);
	}
	public void onBuilt()
	{
		super.onBuilt();
		
		if (parentDialogBox != null) {
			insert(new HTML("&nbsp;"), 0);
			parentDialogBox.center();
			parentDialogBox.show();
		}
	}

	public void buildFromModel() throws Exception
	{
		numberOfTableEntries = termsAndConditionsModels.size();
		numberOfTableColumns = 7;
		if (parentDialogBox != null) numberOfTableColumns = 8;
		extraRows = 0;
		super.buildFromModel();
	}

	public void displayHeader(Grid grid) {
		int colnum = 0;
		if (parentDialogBox != null) grid.setText(0, colnum++, "Select");
		grid.setText(0, colnum++, "Id");
		grid.setText(0, colnum++, "Label");
		grid.setText(0, colnum++, "Summary");
		grid.setText(0, colnum++, "Text");
		grid.setText(0, colnum++, "Used on all new quotes");
		grid.setText(0, colnum++, "Sort Order (within Label)");
		grid.setText(0, colnum++, "Action");
	}

	public void displayRow(Grid grid, int row, int entryIndex) {
		displayRow(grid, row, termsAndConditionsModels.get(entryIndex));
	}

	public void displayRow(Grid grid, int row, TermsAndConditionsModel model) {
		int colnum = 0;
		if (parentDialogBox != null) {
			CheckBox selectBox = new CheckBox();
			elements.put("select-" + row, selectBox);
			elements.put("tAndCId-" + row, new InlineLabel(String.valueOf(model.getId())));
			grid.setWidget(row, colnum++, selectBox);
		}
		grid.setText(row, colnum++, String.valueOf(model.getId()));
		grid.setText(row, colnum++, model.getLabel());
		grid.setHTML(row, colnum++, model.getSummary());
		InlineLabel textLabel = new InlineLabel("text");
		textLabel.setStyleName("ComponentLink");
		textLabel.addStyleName("index:"+(row-1));
		textLabel.addClickHandler(textClickHandler);
		grid.setWidget(row, colnum++, textLabel);

		Grid requiredGrid = new Grid(1, 3);
		if (model.isRequired())
		{
			requiredGrid.setWidget(0, 0, new Image(getImageCommonDirectory() + "icon_status_green.gif"));
			requiredGrid.setWidget(0, 1, new InlineHTML("&nbsp;"));
			Image offImage = new Image(getImageCommonDirectory() + "icon_status_red_off.gif");
			offImage.addStyleName("ComponentLink");
			offImage.addStyleName("index:"+(row-1));
			offImage.addClickHandler(requiredClickHandler);
			requiredGrid.setWidget(0, 2, offImage);
		}
		else
		{
			Image offImage = new Image(getImageCommonDirectory() + "icon_status_green_off.gif");
			offImage.addStyleName("ComponentLink");
			offImage.addStyleName("index:"+(row-1));
			offImage.addClickHandler(requiredClickHandler);
			requiredGrid.setWidget(0, 0, offImage);
			requiredGrid.setWidget(0, 1, new InlineHTML("&nbsp;"));
			requiredGrid.setWidget(0, 2, new Image(getImageCommonDirectory() + "icon_status_red.gif"));
		}
		grid.setWidget(row, colnum++, requiredGrid);

		grid.setText(row, colnum++, String.valueOf(model.getSortOrder()));

		InlineLabel editLabel = new InlineLabel("edit");
		editLabel.setStyleName("ComponentLink");
		editLabel.addStyleName("index:"+(row-1));
		editLabel.addClickHandler(editClickHandler);
		grid.setWidget(row, colnum++, editLabel);
	}

	public List<TermsAndConditionsModel> getTermsAndConditionsModels() {
		return termsAndConditionsModels;
	}

	protected ClickHandler requiredClickHandler = new ClickHandler() {
		public void onClick(ClickEvent event) {
			Widget source = (Widget)event.getSource();
			String stylenames = source.getStyleName();
			int loc = stylenames.indexOf("index:");
			stylenames = stylenames.substring(loc+6);
			loc = stylenames.indexOf(" ");
			if (loc > -1) stylenames = stylenames.substring(0, loc);
			int index = Integer.parseInt(stylenames);
			selectedTermsAndConditionsModel = termsAndConditionsModels.get(index);
			action = ToggleRequired;
			build(true);
		}
	};

	//Insert
	protected ClickHandler editHandler= new ClickHandler() {
		public void onClick(ClickEvent event)
		{
			dialogTermAndCondition(Insert);
		}
	};

	protected ClickHandler editClickHandler = new ClickHandler() {
		public void onClick(ClickEvent event) {
			Widget source = (Widget)event.getSource();
			String stylenames = source.getStyleName();
			int loc = stylenames.indexOf("index:");
			stylenames = stylenames.substring(loc+6);
			loc = stylenames.indexOf(" ");
			if (loc > -1) stylenames = stylenames.substring(0, loc);
			int index = Integer.parseInt(stylenames);
			selectedTermsAndConditionsModel = termsAndConditionsModels.get(index);
			dialogTermAndCondition(Update);
		}
	};

	protected ClickHandler textClickHandler = new ClickHandler() {
		public void onClick(ClickEvent event) {
			Widget source = (Widget)event.getSource();
			String stylenames = source.getStyleName();
			int loc = stylenames.indexOf("index:");
			stylenames = stylenames.substring(loc+6);
			loc = stylenames.indexOf(" ");
			if (loc > -1) stylenames = stylenames.substring(0, loc);
			int index = Integer.parseInt(stylenames);
			dialogText(termsAndConditionsModels.get(index).getText());
		}
	};

	protected void dialogTermAndCondition(String handlerAction)
	{
		boolean actionInsert = false;
		if (handlerAction.equals(Insert)) actionInsert = true; 

		dialogBox = new DialogBox();
		dialogBox.setStyleName(getHandle()+ "TermsAndConditionsDialogBox");
		dialogBox.addStyleName("DialogBox");
		dialogBox.setWidth("400px");

		if (actionInsert) 
			dialogBox.setText("Insert Term or Condition");
		else 
			dialogBox.setText("Update Term or Condition");

		FlowPanel dialogContents = new FlowPanel();
		int numrows = 5;
		Grid grid = new Grid(numrows,2);

		int numrow = 0;

		grid.setText(numrow, 0, "");
		String idStr = "-1";
		if (!actionInsert) idStr = String.valueOf(selectedTermsAndConditionsModel.getId());
		InlineLabel idlabel = new InlineLabel(idStr);
		grid.setWidget(numrow, 1, idlabel);
		elements.put("tAndCId-1", idlabel);

		ListBox labelListBox = new ListBox();
		labelListBox.addItem("Please Select ...", "0");
		if (!actionInsert) labelListBox.setItemSelected(0, 0 == selectedTermsAndConditionsModel.getId());
		List<TermsAndConditionsLabelsModel> labels = termsAndConditionsLabelsComponent.getTermsAndConditionsLabelsModels();
		Iterator<TermsAndConditionsLabelsModel> iter1 = labels.iterator();
		int i = 1;
		while(iter1.hasNext())
		{
			TermsAndConditionsLabelsModel model = iter1.next();
			String label = model.getLabel();
			int id = model.getId();
			labelListBox.addItem(label, String.valueOf(id));
			if (!actionInsert) {
				labelListBox.setItemSelected(i, id == selectedTermsAndConditionsModel.getLabelId());
			}
			i++;
		}
		elements.put("tAndCLabelId-1", labelListBox);
		grid.setText(numrow, 0, "Label:");
		grid.setWidget(numrow, 1, labelListBox);
		numrow++;

		TextBox summaryBox = new TextBox();
		summaryBox.setWidth("350px");
		elements.put("tAndCSummary-1", summaryBox);
		if (!actionInsert) summaryBox.setText(String.valueOf(selectedTermsAndConditionsModel.getSummary()));
		grid.setText(numrow, 0, "Summary:");
		grid.setWidget(numrow, 1, summaryBox);
		numrow++;

		TextArea textTextArea = new TextArea();
		textTextArea.setCharacterWidth(100);
		textTextArea.setVisibleLines(20);
		if (!actionInsert) textTextArea.setText(selectedTermsAndConditionsModel.getTextEdit());
		elements.put("tAndCText-1", textTextArea);
		grid.setText(numrow, 0, "Text:");
		grid.setWidget(numrow, 1, textTextArea);
		numrow++;

		ListBox requiredListBox = new ListBox();
		requiredListBox.addItem("Optional", "0");
		requiredListBox.addItem("Used on all new quotes", "1");
		if (!actionInsert) {
			requiredListBox.setItemSelected(0, !selectedTermsAndConditionsModel.isRequired());
			requiredListBox.setItemSelected(1, selectedTermsAndConditionsModel.isRequired());
		}
		elements.put("tAndCRequired-1", requiredListBox);
		grid.setText(numrow, 0, "Usage:");
		grid.setWidget(numrow, 1, requiredListBox);
		numrow++;

		TextBox sortOrderBox = new TextBox();
		elements.put("tAndCSortOrder-1", sortOrderBox);
		if (!actionInsert) sortOrderBox.setText(String.valueOf(selectedTermsAndConditionsModel.getSortOrder()));
		grid.setText(numrow, 0, "Sort Order:");
		grid.setWidget(numrow, 1, sortOrderBox);
		numrow++;

		dialogContents.add(grid);

		HorizontalPanel buttonPanel = new HorizontalPanel();

		Button closeButton = new Button("close",
				new ClickHandler() {
			public void onClick(ClickEvent event) {
				dialogBox.hide();
			}
		});
		buttonPanel.add(closeButton);
		buttonPanel.add(new InlineHTML("&nbsp;&nbsp;"));

		String editStr = "update";
		if (actionInsert) editStr = "insert";
		Button editButton = new Button(editStr,
				new ClickHandler() {
			public void onClick(ClickEvent event) {
				action = TermsAndConditionsComponent.Update;

				Widget widget = elements.get("tAndCLabelId-1");
				String value = CommonUtils.getValue(widget);
				if (value.equals("0")) {
					Window.alert("Please select a label");
				}
				else {
					elements.put("tAndCDelete-1", null);
					dialogBox.hide();
					build(true);
				}
			}
		});
		buttonPanel.add(editButton);
		if (!actionInsert) {
			buttonPanel.add(new InlineHTML("&nbsp;&nbsp;"));

			Button deleteButton = new Button("delete",
					new ClickHandler() {
				public void onClick(ClickEvent event) {
					action = TermsAndConditionsComponent.Update;
					elements.put("tAndCDelete-1", new InlineLabel("1"));
					dialogBox.hide();
				}
			});
			buttonPanel.add(deleteButton);
		}

		dialogContents.add(buttonPanel);

		dialogBox.setWidget(dialogContents);
		dialogBox.center();
		dialogBox.show();
		labelListBox.setFocus(true);
	}


	protected void dialogText(String text)
	{
		if (textDialogBox == null) textDialogBox = new DialogBox();
		else textDialogBox.clear();
		textDialogBox.setStyleName(getHandle()+ "TermsAndConditionsDialogBox");
		textDialogBox.addStyleName("DialogBox");
		textDialogBox.setWidth("400px");

		FlowPanel dialogContents = new FlowPanel();
		
		dialogContents.add(new HTML(text));

		Button closeButton = new Button("close",
				new ClickHandler() {
			public void onClick(ClickEvent event) {
				textDialogBox.hide();
			}
		});
		dialogContents.add(closeButton);

		textDialogBox.setWidget(dialogContents);
		textDialogBox.center();
		textDialogBox.show();
	}

	public void updateButtonPanel() {
		if (buttonPanel == null)
		{
			buttonPanel = new HorizontalPanel();
			if (parentDialogBox == null) buttonPanel.setStyleName("ZButtons");

			editButton = new Button("insert", editHandler);
			editButton.addStyleName("ComponentLink");
			buttonPanel.add(editButton);
			buttonPanel.add(new InlineHTML("&nbsp;&nbsp;"));
		}
		editButton.setVisible(!edit);
	}
}
